#include "UDPSocketWorker.h"
#include "User.h"
#include <QHostAddress>

extern User user;
extern QQueue<QByteArray> queue_recv;

static const quint16 PORT = 9992;

UDPSocketWorker::UDPSocketWorker(QObject *parent)
    : QObject(parent), socket(nullptr) {
}

UDPSocketWorker::~UDPSocketWorker() {
    if (socket) {
        socket->close();
        socket->deleteLater();
    }
}

void UDPSocketWorker::process() {
    socket = new QUdpSocket(this);

    // 绑定本地端口
    if (!socket->bind(QHostAddress::Any, PORT)) {
        emit errorEmit("UDP bind failed");
        return;
    }

    connect(socket, &QUdpSocket::readyRead,
            this, &UDPSocketWorker::onReadyRead);

    emit connected();
}

void UDPSocketWorker::onReadyRead() {
    while (socket->hasPendingDatagrams()) {
        QByteArray data;
        data.resize(int(socket->pendingDatagramSize()));

        QHostAddress sender;
        quint16 senderPort;

        socket->readDatagram(data.data(), data.size(), &sender, &senderPort);

        if (queue_recv.size() > MAX_QUEUE_SIZE) {
            queue_recv.pop_front();  // 丢掉最旧的
        }

        queue_recv.append(data);
    }
}

void UDPSocketWorker::onError(QAbstractSocket::SocketError error) {
    Q_UNUSED(error)
    emit errorEmit("UDP socket error");
}

void UDPSocketWorker::sendMessage(const MSG &message) {
    if (!socket) return;

    MSG msg = message;
    msg.userId = user.id;
    QByteArray payload = MessageHelper::readMessage(msg);

    // 发往服务端 127.0.0.1:9999
    socket->writeDatagram(payload, QHostAddress("127.0.0.1"), 9999);
}

void UDPSocketWorker::sendPing() {
    if (!socket) return;

    socket->writeDatagram(MessageHelper::makePingMessage(), QHostAddress("127.0.0.1"), 9999);
}